package com.realgodo.site.common;

import java.util.Map;
import java.util.Properties;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.VelocityException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.ui.velocity.VelocityEngineUtils;

/**
 * Class for sending e-mail messages based on Velocity templates or with
 * attachments.
 * 
 * @author Matt Raible
 */
public class MailEngine {

	protected Logger logger = LoggerFactory.getLogger(getClass());

	private String defaultFrom;
	
	private String username;
	
	private String password;
	
	private String from;
	

	private JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
	private VelocityEngine velocityEngine;

	public void setVelocityEngine(VelocityEngine velocityEngine) {
		this.velocityEngine = velocityEngine;
	}

	public void setHost(String host) {
		mailSender.setHost(host);
	}
	
	public void setFrom(String from) {
		this.from = from;
	}

	public void setUsername(String username) {
		this.username=username;
		mailSender.setUsername(username);
	}

	public void setPassword(String password) {
		this.password=password;
		mailSender.setPassword(password);
	}

	public void setSmtpAuth(String smtpAuth) {
		Properties prop=mailSender.getJavaMailProperties();
		prop=prop==null?new Properties():prop;
		prop.setProperty("mail.smtp.auth", smtpAuth);
		mailSender.setJavaMailProperties(prop);
	}

	public void setDefaultFrom(String defaultFrom) {
		this.defaultFrom = defaultFrom;
	}

	/**
	 * Send a simple message based on a Velocity template.
	 * 
	 * @param msg
	 *            the message to populate
	 * @param templateName
	 *            the Velocity template to use (relative to classpath)
	 * @param model
	 *            a map containing key/value pairs
	 */
	@SuppressWarnings("unchecked")
	public void sendMessage(SimpleMailMessage msg, String templateName,Map model) {
		String result = null;

		try {
			result = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, templateName, model);
		} catch (VelocityException e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		MimeMessage mimeMsg = null;
		try {
			mimeMsg = ((JavaMailSenderImpl) mailSender).createMimeMessage();
			MimeMessageHelper helper = new MimeMessageHelper(mimeMsg, true,"utf-8");
			helper.setTo(msg.getTo());
			if (msg.getSubject() != null){
				helper.setSubject(msg.getSubject());
			}
			if (msg.getFrom() != null){
				helper.setFrom(msg.getFrom());
			}else{
				helper.setFrom(from);
			}
			helper.setText(result, true);
		} catch (MessagingException ex) {
			logger.error(ex.getMessage(), ex);
		}
			// msg.setText(result);
			// msg.setFrom(this.defaultFrom);
			logger.debug("from:" + msg.getFrom() + " to:" + msg.getTo()[0]
					+ " host:" + mailSender.getHost() + " user:"
					+ mailSender.getUsername() + " password:"
					+ mailSender.getPassword() + " auth:"
					+ mailSender.getJavaMailProperties().toString() + " text:"
					+ msg.getText());
			((JavaMailSenderImpl) mailSender).send(mimeMsg);
		
			
//		    Transport   transport   =   session.getTransport("smtp");  
//            transport.connect(smtpServer,"att21","212000");  
//            transport.sendMessage(message,meg.getAllRecipients());
	}

	/**
	 * Send a simple message with pre-populated values.
	 * 
	 * @param msg
	 *            the message to send
	 * @throws org.springframework.mail.MailException
	 *             when SMTP server is down
	 */
	public void send(SimpleMailMessage msg) throws MailException {
		try {
			mailSender.send(msg);
		} catch (MailException ex) {
			// log it and go on
			logger.error(ex.getMessage());
			throw ex;
		}
	}

	/**
	 * Convenience method for sending messages with attachments.
	 * 
	 * @param recipients
	 *            array of e-mail addresses
	 * @param sender
	 *            e-mail address of sender
	 * @param resource
	 *            attachment from classpath
	 * @param bodyText
	 *            text in e-mail
	 * @param subject
	 *            subject of e-mail
	 * @param attachmentName
	 *            name for attachment
	 * @throws MessagingException
	 *             thrown when can't communicate with SMTP server
	 */
	public void sendMessage(String[] recipients, String sender,
			ClassPathResource resource, String bodyText, String subject,
			String attachmentName) throws MessagingException {
		MimeMessage message = mailSender.createMimeMessage();

		// use the true flag to indicate you need a multipart message
		MimeMessageHelper helper = new MimeMessageHelper(message, true);

		helper.setTo(recipients);

		// use the default sending if no sender specified
		if (sender == null) {
			helper.setFrom(defaultFrom);
		} else {
			helper.setFrom(sender);
		}

		helper.setText(bodyText);
		helper.setSubject(subject);

		helper.addAttachment(attachmentName, resource);

		mailSender.send(message);
	}

	public void setDefaultEncoding(String defaultEncoding) {
		mailSender.setDefaultEncoding(defaultEncoding);
	}

	public String getUsername() {
		return username;
	}

	public String getPassword() {
		return password;
	}

	
}
